<template>
    <div class="index-page">
        <div class="card-list">
            <el-card class="box-card">
                <div slot="header" class="clearfix">
                    <span>流程</span>
                    <el-tag style="float: right;" size="mini" effect="dark">月</el-tag>
                </div>
                <h2>{{ leaveData.total }}</h2>
                <span>总流程数</span>
                <span style="color: #1890ff;float:right;">
                    <span>{{ formatRate(leaveData.totalRate) }}</span>
                    <span :class="leaveData.totalRate >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></span>
                </span>
            </el-card>
            <el-card class="box-card">
                <div slot="header" class="clearfix">
                    <span>运行</span>
                    <el-tag style="float: right;" type="success" size="mini" effect="dark">全年</el-tag>
                </div>
                <h2>{{ leaveData.lastMonth }}</h2>
                <span>最近一个月请假数</span>
                <span style="color: #13ce66;float:right;">
                    <span>{{ formatRate(leaveData.lastMonthRate) }}</span>
                    <span :class="leaveData.lastMonthRate >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></span>
                </span>
            </el-card>
            <el-card class="box-card">
                <div slot="header" class="clearfix">
                    <span>执行</span>
                    <el-tag style="float: right;" type="success" size="mini" effect="dark">今天</el-tag>
                </div>
                <h2>{{ leaveData.approval }}</h2>
                <span>最近一个月审批数</span>
                <span style="color: #13ce66;float:right;">
                    <span>{{ formatRate(leaveData.approvalRate) }}</span>
                    <span :class="leaveData.approvalRate >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></span>
                </span>
            </el-card>
            <el-card class="box-card">
                <div slot="header" class="clearfix">
                    <span>待办任务数</span>
                    <el-tag style="float: right;" type="danger" size="mini" effect="dark">历史记录</el-tag>
                </div>
                <h2>{{ leaveData.pendingTasks || 0 }}</h2>
                <span>当前待办</span>
                <span style="color: #1890ff;float:right;">
                    <span>{{ formatRate(leaveData.pendingRate || 0) }}</span>
                    <span :class="(leaveData.pendingRate || 0) >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></span>
                </span>
            </el-card>
        </div>
        <div class="chart">
            <el-card>
                <div slot="header" class="clearfix">
                    <span>请假数</span>
                    <span style="float:right;">
                        <el-radio-group v-model="radio4" size="mini" @change="fetchLeaveData">
                            <el-radio-button label="天"></el-radio-button>
                            <el-radio-button label="月"></el-radio-button>
                            <el-radio-button label="年"></el-radio-button>
                        </el-radio-group>
                    </span>
                </div>
                <div style="display: flex;">
                    <div style="width: 70%">
                        <bar-chart ref="barChart"></bar-chart>
                    </div>
                    <div style="width: 30%;">
                        <h2>{{ leaveData.total }}</h2>
                        <div>
                            <span>请假总数</span>
                            <span style="color:#13ce66;float: right;">
                                {{ formatRate(leaveData.totalRate) }}
                                <span :class="leaveData.totalRate >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></span>
                            </span>
                        </div>
                        <el-progress :percentage="Math.abs(leaveData.totalRate)" color="#1ab394" :show-text="false"></el-progress>
                        <h2>{{ leaveData.lastMonth }}</h2>
                        <div>
                            <span>最近一个月请假数</span>
                            <span style="color:#13ce66;float: right;">{{ formatRate(leaveData.lastMonthRate) }}
                                <span :class="leaveData.lastMonthRate >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></span>
                            </span>
                        </div>
                        <el-progress :percentage="Math.abs(leaveData.lastMonthRate)" color="#1ab394" :show-text="false"></el-progress>
                        <h2>{{ leaveData.approval }}</h2>
                        <div>
                            <span>最近一个月审批数</span>
                            <span style="color:#13ce66;float: right;">{{ formatRate(leaveData.approvalRate) }}
                                <span :class="leaveData.approvalRate >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></span>
                            </span>
                        </div>
                        <el-progress :percentage="Math.abs(leaveData.approvalRate)" color="#1ab394" :show-text="false"></el-progress>
                    </div>
                </div>
            </el-card>
        </div>
        <div class="table">
            <el-card>
                <div slot="header" class="clearfix">
                    <span>最近流程申请列表</span>
                    <span style="float:right;">
                        <span class="el-icon-arrow-up"></span>
                        <span class="el-icon-close"></span>
                    </span>
                </div>
                <el-table 
                    :data="tableData" 
                    style="width: 100%"
                    :header-cell-style="{
                        background:'#F5F7FA',
                        color:'#606266',
                        height: '50px',
                        fontWeight: '500',
                        fontSize: '14px',
                        borderRight: '1px solid #EBEEF5'
                    }"
                    :cell-style="{
                        padding: '12px 0',
                        fontSize: '14px'
                    }"
                    :row-style="{
                        height: '55px'
                    }"
                    stripe
                    border>
                    <el-table-column
                        prop="status"
                        label="审批状态"
                        align="center"
                        width="110">
                        <template slot-scope="scope">
                            <el-tag 
                                :type="getStatusType(scope.row.status)"
                                size="mini" 
                                :style="getStatusStyle(scope.row.status)"
                                effect="plain">
                                {{scope.row.status}}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="申请时间"
                        align="center"
                        width="150">
                        <template slot-scope="scope">
                            <span class="time-column">
                                <i class="el-icon-time"></i>
                                {{ formatSimpleTime(scope.row.applyTime) }}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="userName"
                        label="申请人"
                        align="center"
                        width="120">
                        <template slot-scope="scope">
                            <span class="user-name">{{ scope.row.userName }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="deptName"
                        label="部门"
                        align="center"
                        min-width="200">
                        <template slot-scope="scope">
                            <span class="dept-name">{{ scope.row.deptName }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="请假时长"
                        align="center"
                        width="120">
                        <template slot-scope="scope">
                            <el-tooltip :content="scope.row.startTime + ' 至 ' + scope.row.endTime" placement="top">
                                <span class="leave-days">{{ scope.row.leaveDays }}天</span>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="currentTask"
                        label="当前环节"
                        align="center"
                        width="150">
                        <template slot-scope="scope">
                            <el-tooltip effect="dark" :content="'办理人: ' + scope.row.currentAssignee" placement="top">
                                <span :class="['current-task', getTaskClass(scope.row.currentTask)]">
                                    {{ scope.row.currentTask }}
                                </span>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </div>
    </div>
</template>

<script>
import BarChart from './indexBar.vue';
import { getLeaveStatistics } from "@/api/leave";

export default {
    components: {
        BarChart
    },
    data() {
        return {
            radio4: "天",
            tableData: [],
            leaveData: {
                total: 0,
                lastMonth: 0,
                approval: 0,
                totalRate: 0,
                lastMonthRate: 0,
                approvalRate: 0,
                chartData: [],
                pendingTasks: 0,
                pendingRate: 0
            }
        };
    },
    mounted() {
        this.fetchLeaveData();
        this.fetchRecentApplyList();
    },
    watch: {
        radio4(newVal) {
            this.fetchLeaveData();
        }
    },
    methods: {
        fetchLeaveData() {
            getLeaveStatistics({ type: this.radio4 }).then(response => {
                if (response.code === 200) {
                    this.leaveData = response.data;
                    this.$refs.barChart.updateChart(this.leaveData.chartData);
                }
            });
        },
        fetchRecentApplyList() {
            getLeaveStatistics('/recent').then(response => {
                if (response.code === 200) {
                    this.tableData = response.data;
                }
            });
        },
        formatTime(time) {
            if (!time) return '';
            const date = new Date(time);
            const today = new Date();
            const yesterday = new Date(today);
            yesterday.setDate(yesterday.getDate() - 1);

            if (this.isSameDay(date, today)) {
                return this.formatTimeOnly(date);
            } else if (this.isSameDay(date, yesterday)) {
                return '昨天 ' + this.formatTimeOnly(date);
            } else if (date.getFullYear() === today.getFullYear()) {
                return this.formatMonthDay(date) + ' ' + this.formatTimeOnly(date);
            } else {
                return this.formatYearMonthDay(date) + ' ' + this.formatTimeOnly(date);
            }
        },
        formatFullTime(time) {
            if (!time) return '';
            const date = new Date(time);
            return this.formatYearMonthDay(date) + ' ' + this.formatTimeOnly(date);
        },
        formatTimeOnly(date) {
            return String(date.getHours()).padStart(2, '0') + ':' + 
                   String(date.getMinutes()).padStart(2, '0');
        },
        formatMonthDay(date) {
            return (date.getMonth() + 1) + '月' + date.getDate() + '日';
        },
        formatYearMonthDay(date) {
            return date.getFullYear() + '年' + this.formatMonthDay(date);
        },
        isSameDay(date1, date2) {
            return date1.getFullYear() === date2.getFullYear() &&
                   date1.getMonth() === date2.getMonth() &&
                   date1.getDate() === date2.getDate();
        },
        formatSimpleTime(time) {
            if (!time) return '';
            const date = new Date(time);
            return `${date.getMonth() + 1}月${date.getDate()}日 ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
        },
        getStatusType(status) {
            switch (status) {
                case '已完成':
                    return 'success';
                case '已取消':
                    return 'info';
                default:
                    return 'primary';
            }
        },
        getStatusStyle(status) {
            const baseStyle = {
                padding: '0 12px',
                height: '28px',
                lineHeight: '26px',
                borderRadius: '4px'
            };
            switch (status) {
                case '已完成':
                    return {
                        ...baseStyle,
                        background: '#f0f9eb'
                    };
                case '已取消':
                    return {
                        ...baseStyle,
                        background: '#f4f4f5'
                    };
                default:
                    return {
                        ...baseStyle,
                        background: '#ecf5ff'
                    };
            }
        },
        getTaskClass(task) {
            if (task === '流程结束') {
                return 'task-completed';
            } else if (task.includes('审批')) {
                return 'task-approval';
            } else {
                return 'task-progress';
            }
        },
        formatRate(value) {
            if (value === undefined || value === null) return '0%';
            // 如果是整数，不显示小数点
            if (Number.isInteger(value)) {
                return `${value}%`;
            }
            // 如果是小数，最多显示1位小数
            return `${Number(value).toFixed(1)}%`;
        },
        formatNumber(value) {
            if (value === undefined || value === null) return '0';
            // 如果是整数，不显示小数点
            if (Number.isInteger(value)) {
                return value.toString();
            }
            // 如果是小数，最多显示1位小数
            return Number(value).toFixed(1);
        }
    }
};
</script>

<style lang="scss" scoped>
.index-page {
    background-color: #f3f3f4;
    height: 100%;
    padding: 20px;

    .card-list {
        font-size: 14px;
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;
        
        .el-card {
            width: 23%;
            transition: all 0.3s;
            
            &:hover {
                transform: translateY(-5px);
                box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
            }
            h2 {
                font-size: 28px;
                margin: 10px 0;
                color: #303133;
            }
            span {
                &:first-of-type {
                    color: #909399;
                    font-size: 14px;
                }
            }
        }
    }

    .chart, .table {
        margin-top: 20px;
        
        .el-card {
            .el-table {
                margin: 10px 0;
            }
        }
    }
}

::v-deep .el-table {
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0,21,41,.08);
    
    .el-table__header-wrapper {
        border-radius: 4px 4px 0 0;
    }

    // 时间列样式
    .time-column {
        color: #606266;
        i {
            margin-right: 5px;
            color: #909399;
        }
    }

    // 用户名样式
    .user-name {
        font-weight: 500;
        color: #303133;
    }

    // 部门名称样式
    .dept-name {
        color: #606266;
    }

    // 请假天数样式
    .leave-days {
        color: #67c23a;
        font-weight: 500;
    }

    // 当前环节样式
    .current-task {
        font-weight: 500;
        padding: 2px 8px;
        border-radius: 3px;
        
        &.task-completed {
            color: #67c23a;
            background-color: #f0f9eb;
        }
        
        &.task-approval {
            color: #409EFF;
            background-color: #ecf5ff;
        }
        
        &.task-progress {
            color: #e6a23c;
            background-color: #fdf6ec;
        }
    }

    // 表格行样式
    .el-table__row {
        transition: all 0.3s;
        
        &:hover {
            background-color: #f5f7fa !important;
            td {
                background-color: transparent !important;
            }
        }
    }

    // 斑马纹优化
    .el-table__row--striped {
        td {
            background-color: #fafafa;
        }
    }
}

// 工具提示样式优化
::v-deep .el-tooltip__popper {
    font-size: 12px;
    padding: 8px 12px;
    border-radius: 4px;
}
</style>